package lauglog.servlet;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lauglog.bean.UserBean;

/**
 *
 * @author Waseem
 */
@WebServlet(name = "Account", urlPatterns = {"/Account"})
public class AccountServlet extends HttpServlet {
    
     int eventCounter = 0;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            if (action.equalsIgnoreCase("updateProfileInformation"))
                updateProfileInformation(request,response);
            else if (action.equalsIgnoreCase("updateProfilePrivacy")){
                updateProfilePrivacy(request,response);
            } else if (action.equalsIgnoreCase("updatePassword")){
                updatePassword(request,response);
            }
            else;
        } finally {            
            out.close();
        }
    }
    
    private void updatePassword(HttpServletRequest request, HttpServletResponse response){
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con = null;
        try{
            
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //Grab the user id
            UserBean u = (UserBean) request.getSession().getAttribute("user");
            int userId = u.getUserID();
            
            //get password input
            String oldPass = request.getParameter("oldPassword");
            String newPass = request.getParameter("newPassword");
            String confirmPass = request.getParameter("confirmPassword");
            
            //Get username and pass to refresh beans via login
            PreparedStatement getInfo = con.prepareStatement("SELECT UserName,Password FROM users WHERE UserId = ?");
            getInfo.setInt(1, userId);
            ResultSet userInfoRs = getInfo.executeQuery();
            userInfoRs.first();
            
            String username = userInfoRs.getString("UserName");
            String password = userInfoRs.getString("Password");
            
            if(oldPass.equals(password) && newPass.equals(confirmPass)){
                
                //prepare password statement and execute
                PreparedStatement accountPrivacyStatement = con.prepareStatement("UPDATE users SET Password=? WHERE UserId=?");
                accountPrivacyStatement.setString(1,newPass);
                accountPrivacyStatement.setInt(2, userId);
                accountPrivacyStatement.executeUpdate();
                response.sendRedirect("LoginServlet?action=login&username="+username+"&password="+newPass);
            }
            
            //redirect and refresh beans
            response.sendRedirect("LoginServlet?action=login&username="+username+"&password="+password);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
    }
    
    private void updateProfilePrivacy(HttpServletRequest request, HttpServletResponse response){
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con = null;
        try{
            
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //Grab the user id
            UserBean u = (UserBean) request.getSession().getAttribute("user");
            int userId = u.getUserID();
            
            //get privacy data
            int privacy = Integer.parseInt(request.getParameter("privacySelect"));
            
            //prepare privacy statement and execute
            PreparedStatement accountPrivacyStatement = con.prepareStatement("UPDATE privacy_information SET Setting=? WHERE UserId=?");
            accountPrivacyStatement.setInt(1,privacy);
            accountPrivacyStatement.setInt(2, userId);
            accountPrivacyStatement.executeUpdate();
            
            //Get username and pass to refresh beans via login
            PreparedStatement getInfo = con.prepareStatement("SELECT UserName,Password FROM users WHERE UserId = ?");
            getInfo.setInt(1, userId);
            ResultSet userInfoRs = getInfo.executeQuery();
            userInfoRs.first();
            
            String username = userInfoRs.getString("UserName");
            String password = userInfoRs.getString("Password");
            
            //redirect and refresh beans
            response.sendRedirect("LoginServlet?action=login&username="+username+"&password="+password);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
    } 
    
    private void updateProfileInformation(HttpServletRequest request, HttpServletResponse response){
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";
        
        Connection con = null;
        try{
            
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            
            //Grab the user id
            UserBean u = (UserBean) request.getSession().getAttribute("user");
            int userId = u.getUserID();
            
            //Get user table info
            String firstName = request.getParameter("firstName");
            String lastName = request.getParameter("lastName");
            String email = request.getParameter("email");
            
            //prepare user table statement
            PreparedStatement updateUserStatement = con.prepareStatement("UPDATE users SET FirstName=?, LastName=?, Email=? WHERE UserId=?");
            updateUserStatement.setString(1, firstName);
            updateUserStatement.setString(2, lastName);
            updateUserStatement.setString(3, email);
            updateUserStatement.setInt(4, userId);
            updateUserStatement.executeUpdate();
            
            //get profile table info
            Float weight = Float.parseFloat(request.getParameter("weight"));
            Float height = Float.parseFloat(request.getParameter("height"));
            String sex = request.getParameter("sex");
            String city = request.getParameter("city");
            String state = request.getParameter("state");
            String country = request.getParameter("country");
            String education = request.getParameter("education");
            
            //prepare profile_information table statement
            PreparedStatement updateProfileStatement = con.prepareStatement("UPDATE profile_information SET Weight=?,Height=?,Sex=?,City=?,State=?,Country=?,Education=? WHERE UserId=?");
            updateProfileStatement.setFloat(1, weight);
            updateProfileStatement.setFloat(2, height);
            updateProfileStatement.setString(3, sex);
            updateProfileStatement.setString(4, city);
            updateProfileStatement.setString(5, state);
            updateProfileStatement.setString(6, country);
            updateProfileStatement.setString(7, education);
            updateProfileStatement.setInt(8, userId);
            updateProfileStatement.executeUpdate();
            
            //Get username and pass to refresh beans via login
            PreparedStatement getInfo = con.prepareStatement("SELECT UserName,Password FROM users WHERE UserId = ?");
            getInfo.setInt(1, userId);
            ResultSet userInfoRs = getInfo.executeQuery();
            userInfoRs.first();
            
            String username = userInfoRs.getString("UserName");
            String password = userInfoRs.getString("Password");
            
            //redirect and refresh beans
            response.sendRedirect("LoginServlet?action=login&username="+username+"&password="+password);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){
                
            }
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
}
